<?php
declare (strict_types = 1);

namespace app\controller;

use think\Request;
use app\BaseController;
use think\facade\View;
use app\middleware\CheckLogin;
use app\model\MarketPlan as PlanModel;
use app\model\MarketProject as ProjectModel;
use app\model\UploadFile as FileModel;

class Plan extends BaseController
{
    // 注册控制器中间件
    protected $middleware = [CheckLogin::class];
    
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //拉取此前的数据
        $data = PlanModel::select();
        View::assign('data',$data);

        //计算本计划总支持及总预算
        for ($i=0; $i < count($data); $i++) {
            $data[$i]['total_budget'] = ProjectModel::where('plan_id',$data[$i]['id'])->sum('budget');
            $data[$i]['total_support'] = $data[$i]['declare'] * $data[$i]['support'] + $data[$i]['add_support'];
        }

        return view('index'); 
    }


    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return view('create'); 
    }

    /**
     * 上传文件.
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function fileUpload(Request $request)
    {
        // 获取表单上传文件 例如上传了001.jpg
        $files = $request->file('input');
        $plan_id = $request->param('id');

        //判断是否上传文件
        if(!empty($files)){

            //创建文件名数组
            $upload_file = array();
            $upload_file_ID = array();
            for ($i=0; $i < count($files); $i++) { 
                 // 上传到本地服务器
                $url = \think\facade\Filesystem::disk('public')->putFile( 'Manufactor', $files[$i]);
                $upload_file['url'] = $url;
                $upload_file['class'] = "plan";
                $upload_file['ext'] = pathinfo($url, PATHINFO_EXTENSION);
                if(!empty($plan_id)){
                    $upload_file['topid'] = $plan_id;
                }
                $upload_id = FileModel::create($upload_file);
                array_push($upload_file_ID, $upload_id['id']);
            }

            // //获取文件路径
            if(!empty($plan_id)){
                $new_file_id = implode(',', $upload_file_ID);
                $original_data = PlanModel::find($plan_id);
                $data['file_id'] = $original_data['file_id'].",".$new_file_id;
                $data['file'] = FileModel::select($upload_file_ID);
            }else{
                $data['file_id'] = implode(',', $upload_file_ID);
                $data['file'] = FileModel::select($upload_file_ID);
            }
            $data['count'] = count($upload_file_ID);
            $data['result'] = true;
        }else{
            $data['result'] = false;
            $data['reason'] = '没有文件上传';
        }
        return json($data);
    }


    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //获取数据
        $data = $request->param();
        
        //将daterange的数据分解
        $daterange = DateInterval($data['daterange']);
        $data['start_date'] = date('Y-m-d',$daterange['thisStart']);
        $data['end_date'] = date('Y-m-d',$daterange['thisEnd']);

        //文件note保存
        if(!empty($request->param('fileupload_id'))){
            $fileUpload_id = $request->param('fileupload_id');
            $fileUpload_note = $request->param('fileupload_note');

            for ($i=0; $i < count($fileUpload_id); $i++) { 
                $file = FileModel::find($fileUpload_id[$i]);
                $file->note = $fileUpload_note[$i];
                $file->save();
            }
        }
       
        $result = PlanModel::create($data);//调用create方法写入数据库

        if($result == false){
            return 0;
        }else{
            return $result->id;
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //拉取月度计划此前的数据
        $monthPlan = PlanModel::find($id);

        //组装日期范围
        $monthPlan['daterange'] = date('Y-m-d',strtotime($monthPlan['start_date']))." - ". date('Y-m-d',strtotime($monthPlan['end_date']));
        View::assign('monthPlan',$monthPlan);

        //分解厂家文件
        $planFlieId = explode(',', $monthPlan['file_id']);
        $planFlies = FileModel::select($planFlieId);
        View::assign('planFiles',$planFlies);

        //拉取本月度计划下项目的数据
        $project = ProjectModel::where('plan_id',$id)->select();
        View::assign('project',$project);

        return view('read'); 
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //拉取此前的数据
        $data = PlanModel::find($id);

        //组装日期范围
        $data['daterange'] = date('Y-m-d',strtotime($data['start_date']))." - ". date('Y-m-d',strtotime($data['end_date']));
        View::assign('data',$data);

        //分解厂家文件
        $planFileId = explode(',', $data['file_id']);
        $planFiles = FileModel::select($planFileId);
        View::assign('planFiles',$planFiles);

        return view('edit'); 
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //获取数据
        $data = $request->param();
        
        //将daterange的数据分解
        $daterange = DateInterval($data['daterange']);
        $data['start_date'] = date('Y-m-d',$daterange['thisStart']);
        $data['end_date'] = date('Y-m-d',$daterange['thisEnd']);

        //文件note保存
        if(!empty($request->param('fileupload_id'))){
            $fileUpload_id = $request->param('fileupload_id');
            $fileUpload_note = $request->param('fileupload_note');

            for ($i=0; $i < count($fileUpload_id); $i++) { 
                $file = FileModel::find($fileUpload_id[$i]);
                $file->note = $fileUpload_note[$i];
                $file->save();
            }
        }
       
        $result = PlanModel::update($data);//调用create方法写入数据库

        if($result == false){
            return 0;
        }else{
            return $result->id;
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //删除
        $plan = PlanModel::find($id);//删除id号
        $result = $plan->delete();//确认删除结果，返回布尔值
        if($result){
            return "ok";//成功则返回OK
        }else{
            return "false";//失败则返回false
        }
    }
}
